﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace myScheduler
{
    public partial class Scheduler : QT.Windows.Shell.GlassForm
    {
        public static string myDirectory = "Data";
        public static string myDataFile = "Data.xml";

        List<Task> myTask = new List<Task>();

        #region Form

        public Scheduler()
        {
            InitializeComponent();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.Location = new Point(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width-this.Width, 0);
            loadData();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (this.Right > Screen.PrimaryScreen.WorkingArea.Width && this.Top < 0)
            {
                this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, 0);
            }
            else if (this.Left < 0 && this.Top < 0)
            {
                this.Location = new Point(0, 0);
            }
            else if (this.Right > Screen.PrimaryScreen.WorkingArea.Width)
            {
                this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, this.Location.Y);
            }
            else if (this.Left < 0)
            {
                this.Location = new Point(0, this.Location.Y);
            }
            else if (this.Top < 0)
            {
                this.Location = new Point(this.Location.X, 0);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            e.Cancel = true;
            if (MessageBox.Show("确认要退出吗？","系统提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.No) return;
            e.Cancel = false;
        }

        #endregion

        #region Event

        #region PictureBox

        #endregion

        #endregion

        #region Method

        private void loadData()
        {
            if (!File.Exists(myDirectory + @"\" + myDataFile))
            {
                Timer myTimer = new Timer();
                myTimer.ShowDialog();
                myTimer.Dispose();
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(myDirectory + @"\" + myDataFile);
                XmlNodeList xnl = doc.SelectNodes("/root/list/task");

                foreach (XmlNode xn in xnl)
                {
                    try
                    {
                        DateTime datestart = DateTime.Parse(xn.SelectSingleNode("date").Attributes["start"].Value);
                        DateTime dateend = DateTime.Parse(xn.SelectSingleNode("date").Attributes["end"].Value);
                        DateTime timestart = DateTime.Parse(xn.SelectSingleNode("time").Attributes["start"].Value);
                        DateTime timeend = DateTime.Parse(xn.SelectSingleNode("time").Attributes["end"].Value);
                        if (DateTime.Now > (dateend.AddTicks(timeend.TimeOfDay.Ticks))) xn.ParentNode.RemoveChild(xn);

                        string repeattype = xn.SelectSingleNode("repeat").Attributes["type"].Value;
                        int repeatNumber = 1;
                        if (repeattype != "0") repeatNumber = int.Parse(xn.SelectSingleNode("repeat").InnerText);
                        DateTime time = DateTime.Now.Date.AddTicks(timestart.TimeOfDay.Ticks); ;

                        switch (repeattype)
                        {
                            case "6"://年
                                if (DateTime.Now.DayOfYear != datestart.DayOfYear && (DateTime.Now.Year - datestart.Year) % repeatNumber != 0) continue;
                                //ime=datet
                                break;
                            case "5"://月
                                if (DateTime.Now.Day != datestart.Day && (DateTime.Now.Month - datestart.Month) % repeatNumber != 0) continue;
                                break;
                            case "4"://周
                                if (DateTime.Now.DayOfWeek != datestart.DayOfWeek && (GetWeekOfYear(DateTime.Now) - GetWeekOfYear(datestart)) % repeatNumber != 0) continue;
                                break;
                            case "3"://日
                                if ((DateTime.Now.Day - datestart.Day) % repeatNumber != 0) continue;
                                break;
                            case "2"://时
                                while (time < DateTime.Now&&DateTime.Now<=DateTime.Today.AddTicks(dateend.TimeOfDay.Ticks))
                                {
                                    time = time.AddHours(repeatNumber);
                                }
                                break;
                            case "1"://分
                                while (time < DateTime.Now && DateTime.Now <= DateTime.Today.AddTicks(dateend.TimeOfDay.Ticks))
                                {
                                    time = time.AddMinutes(repeatNumber);
                                }
                                break;
                            default://不重复
                                break;
                        }

                        Task tTask = new Task();
                        tTask.guid = xn.Attributes["guid"].Value;
                        tTask.title = xn.SelectSingleNode("title").InnerText;
                        tTask.alerttype = xn.SelectSingleNode("alert").Attributes["type"].Value;
                        tTask.time = time;
                        tTask.path = xn.SelectSingleNode("alert").InnerText;
                        tTask.content = xn.SelectSingleNode("content").InnerText;
                        myTask.Add(tTask);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {
            }

            if (myTask.Count > 0)
            {
                this.llblTask1.Text = "["+myTask[0].time.ToString("HH:mm:ss")+"]"+myTask[0].title;
            }

            //ResourceWriter rw = new ResourceWriter("Faces.resources");
            //string AutoHide = "0";
            //rw.AddResource("AutoHide", AutoHide);
            //rw.Generate();
            //rw.Close();
        }

        private bool CheckExsits(string file)
        {
            if (!Directory.Exists(myDirectory)) Directory.CreateDirectory(myDirectory);

            if (File.Exists(file)) return true;
            else return false;
        }

        private static int GetWeekOfYear(DateTime myDate)
        {
            //一.找到第一周的最后一天（先获取1月1日是星期几，从而得知第一周周末是几）
            int firstWeekend = 7 - Convert.ToInt32(DateTime.Parse(myDate.Year + "-1-1").DayOfWeek);

            //二.获取今天是一年当中的第几天
            int currentDay = DateTime.Today.DayOfYear;
            //三.（今天 减去 第一周周末）/7 等于 距第一周有多少周 再加上第一周的1 就是今天是今年的第几周了
            //    刚好考虑了惟一的特殊情况就是，今天刚好在第一周内，那么距第一周就是0 再加上第一周的1 最后还是1
            return Convert.ToInt32(Math.Ceiling((currentDay - firstWeekend) / 7.0)) + 1;
        }

        #endregion

        #region ContextMenuStrip

        private void mainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Visible = true;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion
    }

    public struct Task
    {
        /// <summary>
        /// Guid
        /// </summary>
        public string guid;
        /// <summary>
        /// 标题
        /// </summary>
        public string title;
        /// <summary>
        /// 闹钟时间
        /// </summary>
        public DateTime time;
        /// <summary>
        /// 提示类型
        /// </summary>
        public string alerttype;
        /// <summary>
        /// 音乐路径
        /// </summary>
        public string path;
        /// <summary>
        /// 备注
        /// </summary>
        public string content;
    }
}
